package com.hyy.backend.service.impl;

import com.hyy.backend.dao.UserMapper;
import com.hyy.backend.entity.UserInfo;
import com.hyy.backend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public UserInfo login(String userName, String password) {
        UserInfo user = userMapper.selectByUserName(userName);
        if (user != null && passwordEncoder.matches(password, user.getPassword())) {
            return user;
        }
        return null;
    }

    @Override
    public UserInfo selectByUserName(String userName) {
        return userMapper.selectByUserName(userName);
    }

    @Override
    public int insertUser(UserInfo user) {
        // 加密密码
        String encodedPassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodedPassword);

        // 设置默认状态
        user.setActive(true);
        return userMapper.insertUser(user);
    }

    @Override
    public List<UserInfo> findAllUsers() {
        return userMapper.findAllUsers();
    }

    @Override
    public UserInfo findUserById(int userId) {
        return userMapper.selectById(userId);
    }

    @Transactional
    @Override
    public void updateUser(UserInfo user) {
        userMapper.updateUser(user);
    }

    @Transactional
    @Override
    public void updateUserStatus(int userId, boolean active) {
        userMapper.updateUserStatus(userId, active);
    }

    @Transactional
    @Override
    public void updateUserAvatar(UserInfo user) {
        userMapper.updateUserAvatar(user);
    }

    @Transactional
    @Override
    public boolean updateUserInfo(UserInfo userInfo) {
        return userMapper.updateUserInfo(userInfo) > 0;
    }

    @Transactional
    @Override
    public boolean updatePassword(int userId, String oldPassword, String newPassword) {
        UserInfo user = userMapper.selectById(userId);
        if (user == null) return false;
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            return false;
        }
        String encodedNewPassword = passwordEncoder.encode(newPassword);
        return userMapper.updatePassword(userId, encodedNewPassword) > 0;
    }

}
